package com.gwall.test.plateform.shenyu;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class AfterMigrateDmsDemo {

    static String SK = "FDCE3FDCB7CD43B2A44445B356CA5A1C";

    public String getSignFromParamMap(HashMap<String, String> paramMap) throws Exception {
        Collection<String> params = paramMap.values();
        //值排序
        params = params.stream().filter(StrUtil::isNotEmpty).sorted().collect(Collectors.toList());
        //拼接
        String signString = StrUtil.join("", params);
        log.info("request sign string:{}", signString);

        return this.digestHex(signString, "hmac-sha256", SK);
    }

    /**
     * 对字符串按算法计算哈希值.
     *
     * @param signString 待签名字符串
     * @param algorithm  签名算法
     * @param apiSecret  api secret
     * @return sign
     */
    private String digestHex(final String signString, final String algorithm, final String apiSecret) throws Exception {
        if ("hmac-sha256".equals(algorithm)) {
            //默认hmac sha256
            Mac hasher = Mac.getInstance("HmacSHA256");
            hasher.init(new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] hash = hasher.doFinal(signString.getBytes(StandardCharsets.UTF_8));
            return DatatypeConverter.printBase64Binary(hash);
            // return DigestUtils.md5Hex(hash).toUpperCase();
        }
        throw new RuntimeException("不支持的签名算法.");
    }


    public static void main(String[] args) throws Exception {

        String base  = "https://app-apigw-prod-idc.ifyou.net";
        String path  = "/isc/web/ldm_dictionary_value/query_cache";
//        String path  = "/appman/api/healthy";

        String timestamp = String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        String AK = "1E9A897A19D747338C6A7E6AA3687B05";

        HashMap<String, String> paramMap = new HashMap<>();

        paramMap.put("path", path);
        paramMap.put("x-if-timestamp", timestamp);
        paramMap.put("x-if-algorithm", "hmac-sha256");
        paramMap.put("x-if-api-key", AK);
        paramMap.put("httpMethod", "post");

        AfterMigrateDmsDemo model = new AfterMigrateDmsDemo();

        String sign = model.getSignFromParamMap(paramMap);

        log.info("sign:{}", sign);




        String fullUrl = base + path;

        System.out.println("fullUrl = " + fullUrl);

        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("path", path);
        headerMap.put("x-if-timestamp", timestamp);
        headerMap.put("x-if-algorithm", "hmac-sha256");
        headerMap.put("x-if-api-key", AK);
        headerMap.put("x-if-sign", sign);

        headerMap.put("Content-Type", "application/json;charset=UTF-8");

        List<String> dictCodeList = new ArrayList<>();

        dictCodeList.add("MaterialDocument");
        dictCodeList.add("OrderState");

        String jsonStr = JSONUtil.toJsonStr(dictCodeList);

        // 请求 GET
        HttpResponse response = HttpRequest.post(fullUrl)
                // .form(jsonStr) // url 上加参数
                .body(jsonStr)
                .addHeaders(headerMap)
                .timeout(20000).execute();

        System.out.println(response);
    }

}
